package com.tjp.eight.ui.fragment.personsetting;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.kyleduo.switchbutton.SwitchButton;
import com.tjp.eight.R;
import com.tjp.eight.ResultModel;
import com.tjp.eight.RxBus;
import com.tjp.eight.constant.ConstantUtils;
import com.tjp.eight.ui.fragment.BaseFragment;
import com.tjp.eight.ui.fragment.bindingphone.ActivityBindingPhone;
import com.tjp.eight.ui.fragment.bindingphone.BindingPhoneEvent;
import com.tjp.eight.ui.fragment.modyname.ActivityModyName;
import com.tjp.eight.ui.fragment.modyname.ModifyNameEvent;
import com.tjp.eight.utils.ActivityUtils;
import com.tjp.eight.utils.AppUtils;
import com.tjp.eight.utils.BitmapHelper;
import com.tjp.eight.utils.DescriptUtils;
import com.tjp.eight.utils.FileUtils;
import com.tjp.eight.utils.IsSuccessUtils;
import com.tjp.eight.utils.SharePreferencesUtils;
import com.tjp.eight.utils.StringUtils;
import com.tjp.eight.utils.ToatUtils;
import com.tjp.eight.views.CircleImageView;
import com.tjp.eight.views.SelectPicDialog;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.w3c.dom.Text;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Random;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.http.Body;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Created by Administrator on 2017/3/1.
 */
public class FragmentPersonSetting extends BaseFragment<PersonSettingPresenter> implements PersonSettingView {
    private SelectPicDialog selectPicDialog;
    File filePath;//
    File fileName;//
    String tempfileName;
    private String appNmae = "八秒视频";
    String imgPath = "";
    Uri uri;
    private static final int CAMERA_REQUEST = 0x108;//从图库获取
    private static final int CAMERA_REQUESTD = 0x109;//从拍照获取
    @Bind(R.id.rl_pic)
    RelativeLayout rl_pic;
    @Bind(R.id.civ_user_pic)
    CircleImageView civ_user_pic;
    @Bind(R.id.ed_nick_name)
    EditText ed_nick_name;
    @Bind(R.id.rb_man)
    RadioButton rb_man;
    @Bind(R.id.rb_women)
    RadioButton rb_women;
    @Bind(R.id.rb_xing_zuo)
    RadioButton rb_xing_zuo;
    @Bind(R.id.tv_invite_code)
    TextView tv_invite_code;
    @Bind(R.id.ed_invite_code)
    EditText ed_invite_code;
    @Bind(R.id.sb_is_phone)
    SwitchButton sb_is_phone;
    @Bind(R.id.sb_is_wx)
    SwitchButton sb_is_wx;
    @Bind(R.id.rl_mody_pass)
    RelativeLayout rl_mody_pass;
    @Bind(R.id.rl_bind_phone)
    RelativeLayout rl_bind_phone;
    @Bind(R.id.rl_bind_wx)
    RelativeLayout rl_bind_wx;


    private String curentSex = "";
    private DatePickerDialog datePickerDialog;

    private Observable<ModifyNameEvent> observable;
    private Observable<InviteCodeEvent> observableInviteCode;
    private Observable<BindingPhoneEvent> observableBindingPhone;

    @Override
    protected PersonSettingPresenter createPresenter() {
        return new PersonSettingPresenter(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = super.onCreateView(inflater, container, savedInstanceState);
        if (contentView == null) {
            contentView = inflater.inflate(R.layout.fragment_person_setting, container, false);
        }
        ButterKnife.bind(this, contentView);
        initViews();
        regRxBus();
        return contentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        presenter.loadData(getPJson());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                case CAMERA_REQUEST:
                    if (data == null)
                        return;

                    try {
//                        Uri uri = data.getData();
                        Uri uri = geturi(data);
                        if (uri == null) {
                            ToatUtils.toastSuccess(getContext(), "无法获取图片");
                            return;
                        }
                        Bitmap bitmap = BitmapHelper.compressBitmap(FileUtils.imgPath(getActivity(), uri), 320, 320);
                        bitmap = ThumbnailUtils.extractThumbnail(bitmap, 320, 320);
                        imgPath = FileUtils.saveBitmapFile(getActivity(), bitmap, "user_pic.jpg");
                        bitmap = BitmapFactory.decodeFile(imgPath);
                        civ_user_pic.setImageBitmap(bitmap);
                    } catch (IllegalAccessException e) {

                    }
                    if (!StringUtils.isNullOrEmpty(imgPath)) {
                        String uid = SharePreferencesUtils.getUid();
                        String key = SharePreferencesUtils.getLoginKey();
                        presenter.uploadPic(uid, key, imgPath);
                    }
                    break;
                case CAMERA_REQUESTD:
                    File f = FileUtils.saveBitmap(getActivity(), fileName);
                    imgPath = f.getPath();
                    Bitmap bitmap1 = BitmapHelper.compressBitmap(fileName.getPath(), 320, 320);
                    bitmap1 = ThumbnailUtils.extractThumbnail(bitmap1, 320, 320);
                    bitmap1 = BitmapFactory.decodeFile(imgPath);
                    civ_user_pic.setImageBitmap(bitmap1);
                    if (!StringUtils.isNullOrEmpty(imgPath)) {
                        String uid = SharePreferencesUtils.getUid();
                        String key = SharePreferencesUtils.getLoginKey();
                        presenter.uploadPic(uid, key, imgPath);
                    }
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        unRegRxBus();
    }

    @OnClick(R.id.rl_pic)
    public void selectUserPic() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1222);
            }
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 1222);
            }
        }
        showSelectDialog();
    }

    @OnClick(R.id.rl_bind_phone)
    void bindphone() {
        getActivity().startActivity(new Intent(getActivity(), ActivityBindingPhone.class));
    }

    @OnClick(R.id.tv_invite_code)
    void copyCode() {
        ClipboardManager clipboardManager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText("", tv_invite_code.getText().toString());
        clipboardManager.setPrimaryClip(clipData);
        ToatUtils.toastSuccess(getContext(), "邀请码复制成功");
    }

    @OnClick(R.id.rl_modify_name)
    void modifyName() {
        getActivity().startActivity(new Intent(getActivity(), ActivityModyName.class));
    }

    @OnClick(R.id.rl_input_code)
    void inputCode() {
        getActivity().startActivity(new Intent(getActivity(), ActivityInputCode.class));
    }

    /**
     * 解决小米手机上获取图片路径为null的情况
     *
     * @param intent
     * @return
     */
    public Uri geturi(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = getActivity().getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }

    private void showSelectDialog() {
        if (selectPicDialog == null) {
            selectPicDialog = new SelectPicDialog(getContext());
            selectPicDialog.setOnItemClickListener(new SelectPicDialog.OnItemClickListener() {
                @Override
                public void onItemClick(int type) {
                    if (type == SelectPicDialog.TYPE_PIC) {
                        showPic();
                    } else {
                        showXJ();
                    }
                }
            });
        }
        selectPicDialog.show();
    }

    private void showPic() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, CAMERA_REQUEST);
    }

    private void showXJ() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            filePath = new File(Environment.getExternalStorageDirectory()
                    .getAbsoluteFile()
                    + "/"
                    + appNmae
                    + File.separator
            );
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
        } else {
            filePath = new File(Environment.getRootDirectory()
                    .getAbsoluteFile()
                    + "/"
                    + appNmae
                    + File.separator
            );
            if (!filePath.exists())
                filePath.mkdirs();
        }

        Intent intent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        String format = "yyyy-MM-ddHH:mm:ss";
        SimpleDateFormat sm = new SimpleDateFormat(format);
        tempfileName = sm.format(new Date()) + ".jpg";
        fileName = new File(filePath, tempfileName);

        uri = Uri.fromFile(fileName);
        ContentValues v = new ContentValues();
        v.put(MediaStore.Audio.Media.TITLE, tempfileName);
        intent.putExtra(MediaStore.Images.Media.ORIENTATION, v);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);

        startActivityForResult(intent, CAMERA_REQUESTD);
    }

    private void initViews() {
    }

    private String getPJson() {
        PSettingPModel model = new PSettingPModel();
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    @OnClick(R.id.rl_mody_pass)
    void onStartPass() {
        ActivityUtils.startModyPass(getContext());
    }

    @OnClick({R.id.rl_xing_zuo, R.id.rb_xing_zuo})
    void onXingZuo() {
        showDatePic();
    }

    @OnClick(R.id.rl_bind_wx)
    void bindingWx() {
        UMShareAPI.get(getContext()).getPlatformInfo(getActivity(), SHARE_MEDIA.WEIXIN, umAuthListenerMsg);
    }

    private UMAuthListener umAuthListenerMsg = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            BindingWxModel model = new BindingWxModel();
            model.openid = map.get("openid");
            model.unionid = map.get("unionid");
            model.uid = SharePreferencesUtils.getUid();
            model.loginkey = SharePreferencesUtils.getLoginKey();


            Gson gson = new Gson();
            String json = gson.toJson(model);

            presenter.bindingWx(json);
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            Toast.makeText(getContext(), "授权失败", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            Toast.makeText(getContext(), "授权取消", Toast.LENGTH_LONG).show();
        }
    };

    @Override
    public void loadData(PersonModel model) {
        if (model == null) return;
        if (model.data != null) {
            Glide.with(getContext()).load(model.data.iconurl).error(R.drawable.icon_login).into(civ_user_pic);
            ed_nick_name.setText("" + model.data.name);
            setManWomen(model.data.sex);
            setXingZuo(model.data.constellation);
            tv_invite_code.setText("" + model.data.invite_code);
            if (StringUtils.isNullOrEmpty(model.data.mobile)) {
                sb_is_phone.setChecked(false);
                rl_bind_phone.setEnabled(true);
                rl_bind_phone.setClickable(true);
                rl_mody_pass.setVisibility(View.GONE);
            } else {
                rl_bind_phone.setClickable(false);
                rl_bind_phone.setEnabled(false);
                sb_is_phone.setChecked(true);
                rl_mody_pass.setVisibility(View.VISIBLE);
            }
            if (StringUtils.isNullOrEmpty(model.data.openid)) {
                sb_is_wx.setChecked(false);
                rl_bind_wx.setClickable(true);
                rl_bind_wx.setEnabled(true);
            } else {
                rl_bind_wx.setClickable(false);
                rl_bind_wx.setEnabled(false);
                sb_is_wx.setChecked(true);
            }
        }
    }

    private void setManWomen(String sex) {
        if ("男".equals(sex)) {
            rb_man.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.man_enable), null, null, null);
            rb_women.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.woman_unable), null, null, null);
        } else if ("女".equals(sex)) {
            rb_man.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.man_unable), null, null, null);
            rb_women.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.woman_enable), null, null, null);
        }
    }

    @OnClick({R.id.rb_man, R.id.rb_women})
    void onClickMW() {
        String temp_sex = "男";
        if (rb_man.isChecked()) {
            temp_sex = "男";
        } else if (rb_women.isChecked()) {
            temp_sex = "女";
        }
        setManWomen(temp_sex);
        curentSex = temp_sex;
        presenter.modifySex(getSexPJson(temp_sex));
    }

    private String getSexPJson(String sex) {
        SexPModel model = new SexPModel();

        model.gender = sex;
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    private void setXingZuo(String xName) {
        if (StringUtils.isNullOrEmpty(xName)) return;
        switch (xName) {
            case "白羊座"://03月21日─04月20日 Aries
                rb_xing_zuo.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.aries), null, null, null);
                rb_xing_zuo.setText("" + xName);
                break;
            case "金牛座"://04月21日─05月20日 Taurus
                rb_xing_zuo.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.taurus), null, null, null);
                rb_xing_zuo.setText("" + xName);
                break;
            case "双子座"://05月21日─06月21日 Gemini
                rb_xing_zuo.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.gemini), null, null, null);
                rb_xing_zuo.setText("" + xName);
                break;
            case "巨蟹座"://06月22日─07月22日 Cancer
                rb_xing_zuo.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.cancer), null, null, null);
                rb_xing_zuo.setText("" + xName);
                break;
            case "狮子座"://07月23日─08月22日 Leo
                rb_xing_zuo.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.leo), null, null, null);
                rb_xing_zuo.setText("" + xName);
                break;
            case "处女座"://08月23日─09月22日 Virgo
                rb_xing_zuo.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.virgo), null, null, null);
                rb_xing_zuo.setText("" + xName);
                break;
            case "天枰座"://09月23日─10月22日 Libra
                rb_xing_zuo.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.libra), null, null, null);
                rb_xing_zuo.setText("" + xName);
                break;
            case "天蝎座"://10月23日─11月21日 Scorpio
                rb_xing_zuo.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.scorpio), null, null, null);
                rb_xing_zuo.setText("" + xName);
                break;
            case "射手座"://11月22日─12月21日 Sagittarius
                rb_xing_zuo.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.sagittarius), null, null, null);
                rb_xing_zuo.setText("" + xName);
                break;
            case "摩羯座"://12月22日─01月19日 Capricorn
                rb_xing_zuo.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.capricorn), null, null, null);
                rb_xing_zuo.setText("" + xName);
                break;
            case "水瓶座"://01月20日─02月18日 Aquarius
                rb_xing_zuo.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.aquarius), null, null, null);
                rb_xing_zuo.setText("" + xName);
                break;
            case "双鱼座"://    02月19日─03月20日 Pisces
                rb_xing_zuo.setCompoundDrawablesWithIntrinsicBounds(getActivity().getResources().getDrawable(R.drawable.pisces), null, null, null);
                rb_xing_zuo.setText("" + xName);
                break;
        }
    }

    private void regRxBus() {
        observable = RxBus.getInstance().register(ModifyNameEvent.class);
        observable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<ModifyNameEvent>() {
            @Override
            public void call(ModifyNameEvent modifyNameEvent) {
                if (modifyNameEvent != null && !StringUtils.isNullOrEmpty(modifyNameEvent.getName())) {
                    ed_nick_name.setText(modifyNameEvent.getName());
                    SharePreferencesUtils.setName(modifyNameEvent.getName());
                }
            }
        });
        observableInviteCode = RxBus.getInstance().register(InviteCodeEvent.class);
        observableInviteCode.observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<InviteCodeEvent>() {
            @Override
            public void call(InviteCodeEvent codeEvent) {
                if (codeEvent != null && !StringUtils.isNullOrEmpty(codeEvent.getCode())) {
                    ed_invite_code.setText(codeEvent.getCode());
                }
            }
        });
        observableBindingPhone = RxBus.getInstance().register(BindingPhoneEvent.class);
        observableBindingPhone.observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<BindingPhoneEvent>() {
            @Override
            public void call(BindingPhoneEvent codeEvent) {
                if (codeEvent != null && !StringUtils.isNullOrEmpty(codeEvent.getPhone())) {
                    sb_is_phone.setChecked(true);
                }
            }
        });
    }

    private void unRegRxBus() {
        if (observable != null) {
            RxBus.getInstance().unregister(ModifyNameEvent.class, observable);
        }
        if (observableInviteCode != null) {
            RxBus.getInstance().unregister(InviteCodeEvent.class, observableInviteCode);
        }
    }

    private void showDatePic() {
        if (datePickerDialog == null) {
            Calendar mycalendar = Calendar.getInstance();

            int year = mycalendar.get(Calendar.YEAR); //获取Calendar对象中的年
            int month = mycalendar.get(Calendar.MONTH);//获取Calendar对象中的月
            int day = mycalendar.get(Calendar.DAY_OF_MONTH);//获取这个月的第几天
            datePickerDialog = new DatePickerDialog(getContext(), dListener, year, month, day);
        }
        datePickerDialog.show();
    }

    private String getXPjson(String xName) {
        XingZuoPModel model = new XingZuoPModel();
        model.constellation = xName;
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    DatePickerDialog.OnDateSetListener dListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            String s = AppUtils.getConstellation(month + 1, dayOfMonth);
            setXingZuo(s);
            presenter.uploadXingZuo(getXPjson(s));
        }
    };

    @Override
    public void loadFail(String msg) {
        ToatUtils.toastSuccess(getContext(), msg);
    }

    @Override
    public void uploadSuccess(UploadPicRModel model) {
        if (model != null) {
            ToatUtils.toastSuccess(getContext(), model.msg);
            if (IsSuccessUtils.isSuccess(model.result)) {
                RxBus.getInstance().post(new PicEvent());
            }
        }
    }

    @Override
    public void xingZuoSuccess(ResultModel model) {
        if (model != null) {
            ToatUtils.toastSuccess(getContext(), model.msg);
        }
    }

    @Override
    public void sexSuccess(ResultModel model) {
        if (model != null) {
            ToatUtils.toastSuccess(getContext(), model.msg);
            if (IsSuccessUtils.isSuccess(model.result)) {
                RxBus.getInstance().post(new SexEvent(curentSex));
            }
        }
    }

    @Override
    public void bindingSuccess(ResultModel model) {
        if (model != null) {
            ToatUtils.toastSuccess(getContext(), model.msg);
            if (IsSuccessUtils.isSuccess(model.result)) {
                sb_is_wx.setChecked(true);
                rl_bind_wx.setClickable(false);
                rl_bind_wx.setEnabled(false);
            } else {
                sb_is_wx.setChecked(false);
                rl_bind_wx.setClickable(true);
                rl_bind_wx.setEnabled(true);
            }
        }
    }
}
